<?php

namespace App\Admin\Forms\User;

use App\Models\AdminRoleUser;
use App\Models\AdminUser;
use App\Models\User;
use App\Models\UserTree;
use App\Services\Base\HelpService;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Models\Role;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class CreateAgentForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        try {
            DB::beginTransaction();
            $parent_admin_id = Admin::user()->id;
            $password = Hash::make($input['password']);
            $admin_user = AdminUser::query()->create([
                'username' => $input['username'],
                'password' => $password,
                'name' => $input['name'],

            ]);

            $roles = explode(",", $input['roles']);
            $data = [];
            foreach ($roles as $v) {
                $data[] = [
                    'role_id' => $v,
                    'user_id' => $admin_user->id
                ];
            }

            DB::table("admin_role_users")->insert($data);
            $model_user = new User();
            $i = 0;
            do {
                $code = g_generate_code(6);
            } while ($i++ < 5 && User::oneByInviteCode($code));
            if (!$code) {
                throw new \InvalidArgumentException("g_generate_code failed");
            }

            if (Admin::user()->isAdministrator()) { //如果是管理员
                $parent_admin_id = 1;
            }

            $rid = 1;
            if ($parent_admin_id != 1) {
                /**
                 * @var User $user_parent
                 */
                $user_parent = User::whereAdminId($parent_admin_id)->first();
                $rid = $user_parent->id;
                $agent_path = $user_parent->agent_path . "," . $parent_admin_id;
            } else {
                $agent_path = "1";
            }

            $model_user->fill([
                'admin_id' => $admin_user->id,
                'password' => $password,
                'rid' => $rid, // 父节点
                'status' => STATUS_ENABLED, // 状态
                'invite_code' => $code, // 邀请码
                'nickname' => $input['name'],
                'name' => "@{$input['username']}",
                'email' => "@{$input['username']}",
                'agent_path' => $agent_path
            ])->save();

            UserTree::buildUserTree($model_user->id, $model_user->rid);
            DB::commit();
            $op_result = true;
        } catch (\Exception $e) {
            HelpService::forceLog($e);
            DB::rollBack();
            $op_result = false;
        }

        if ($op_result) {
            return $this
                ->response()
                ->success('执行成功')
                ->refresh();
        } else {
            return $this
                ->response()
                ->error('执行失败');
        }
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $userTable = config('admin.database.users_table');
        $connection = config('admin.database.connection');

        $id = $this->getKey();


        $this->text('username', trans('admin.username'))
            ->required()
            ->creationRules(['required', "max:14", "alpha_num", "unique:{$connection}.{$userTable}"])
            ->updateRules(['required', "max:14", "alpha_num", "unique:{$connection}.{$userTable},username,$id"]);
        $this->text('name', trans('admin.name'))->required()
            ->maxLength(14)
            ->rules(["alpha_num", 'max:14']);

        if ($id) {
            $this->password('password', trans('admin.password'))
                ->minLength(5)
                ->maxLength(20)
                ->customFormat(function () {
                    return '';
                });
        } else {
            $this->password('password', trans('admin.password'))
                ->required()
                ->minLength(5)
                ->maxLength(20);
        }

        $this->password('password_confirmation', trans('admin.password_confirmation'))->same('password');
        if (config('admin.permission.enable')) {
            $this->select('roles', trans('admin.roles'))
                ->options(function () {
                    $roleModel = config('admin.database.roles_model');
                    Log::error($roleModel::where('id', "!=", 1)->pluck('name', 'id'));
                    return $roleModel::where('id', "!=", 1)->pluck('name', 'id');
                })
                ->customFormat(function ($v) {
                    if ($v) {
                        return array_column($v, 'id');
                    }
                })->required();
        }

    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
        ];
    }
}
